<template>
  <a-select
    v-model:value="localValue"
    show-search
    placeholder="请选择品牌"
    allow-clear
    option-filter-prop="label"
    :filter-option="filterOption"
    :loading="loading"
    @search="handleSearch"
    @popupScroll="handlePopupScroll"
    @change="handleChange"
    :style="style"
  >
    <a-select-option
      v-for="item in brandList"
      :key="item.id"
      :value="item.id"
    >
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>

<script>
import { defineComponent, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import * as api from '@/api/base-data/product/brand';

export default defineComponent({
  name: 'MobileProductBrandSelector',
  props: {
    value: {
      type: [String, Number],
      default: '',
    },
    style: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, { emit }) {
    const loading = ref(false);
    const brandList = ref([]);
    const localValue = ref(props.value);
    const searchText = ref('');

    // 监听props.value变化，同步到localValue
    watch(
      () => props.value,
      (newValue) => {
        localValue.value = newValue;
      },
      { immediate: true }
    );

    // 加载品牌数据
    const loadData = async (reset = false) => {
      if (reset) {
        brandList.value = [];
      }
      
      loading.value = true;
      try {
        const params = {
          pageNum: 1,
          pageSize: 99999,
          available: true,
          name: searchText.value,
        };
        
        const response = await api.selector(params);
        const data = response.datas || [];
        brandList.value = data;
      } catch (error) {
        message.error('加载品牌数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = (value) => {
      searchText.value = value;
      loadData(true);
    };

    // 滚动加载更多
    const handlePopupScroll = (e) => {
      const { target } = e;
      const { scrollTop, scrollHeight, clientHeight } = target;
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        // 由于pageSize已经设为很大值，暂时不需要分页加载
      }
    };

    // 选择变化处理
    const handleChange = (value) => {
      localValue.value = value;
      emit('update:value', value);
    };

    // 过滤选项
    const filterOption = (input, option) => {
      return (
        option?.children?.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    };

    // 初始化加载数据
    loadData();

    return {
      loading,
      brandList,
      localValue,
      handleSearch,
      handlePopupScroll,
      handleChange,
      filterOption,
    };
  },
});
</script>

<style scoped lang="less">
:deep(.ant-select-selector) {
  width: 100%;
  min-height: 32px;
}

:deep(.ant-select-selection-item) {
  height: auto;
  min-height: 24px;
  line-height: 24px;
}
</style>